<template>
  <div
    class="map-com monitor-map"
    id="car-map"
    :style="{ height: maxHeight + 'px' }"
  >
    <!-- 地图容器 -->
    <div id="container" class="container"></div>
    <div class="tool-right">
      <img
        class="tool-btn"
        @click="toogleLayer"
        v-if="isSatellite"
        src="~@/assets/img/map/satellite-active.png"
      />
      <img
        class="tool-btn"
        @click="toogleLayer"
        v-else
        src="~@/assets/img/map/satellite.png"
      />
      <img
        class="tool-btn"
        @click="toogleFullScreen"
        src="~@/assets/img/common/full-screen.png"
      />
    </div>

    <!-- 在线车辆 -->
    <div class="weatherDiv">
      <div style="margin-bottom:10px;font-size:16px">今日天气:</div>
      <div style="margin-bottom:10px;">
        {{ weatherInfo.weather }}｜温度:{{ weatherInfo.temperature }}℃ | 风力:{{
          weatherInfo.windPower
        }}级 ｜ 风向:{{ weatherInfo.windDirection }}
      </div>

      <div style="margin-bottom:5px;font-size:16px">车辆信息:</div>
      <div style="width:100%;display:flex;justify-content: space-between;margin-bottom: 10px;">
        <div class="carContainer"><img :src="carImg0" class="carImage"/><span>运行中(辆)：{{ onlineCarInfo.onlineCarCount }}</span></div>
        <div class="carContainer"> <img :src="carImg3" class="carImage"/><span>离线(辆)：{{ onlineCarInfo.offlineCarCount }}</span></div>
      </div>

       <div style="margin-bottom:5px;font-size:16px">液位计信息:</div>
        <div style="">
          <img :src="conImg2" alt="" style="width:26px;" >
          <span>在线: {{ onlineContainer }}</span>
        </div>
    </div>

    <!-- 固定定位表格的图标 -->
    <div
      class="iconFrom"
      @click="collectShow = !collectShow"
      v-show="!collectShow"
    >
      <i class="iconfont iconche" style="font-size: 18px"></i>工作台
      <i class="iconfont iconxiangshang"></i>
    </div>

    <transition name="collectShow">
      <div class="collect" v-show="collectShow">
        <div class="btn" @click="collectShow = !collectShow">
          <i class="iconfont iconche" style="font-size: 18px"></i>工作台
          <i class="iconfont iconzhankai"></i>
        </div>
        <el-tabs
          v-model="activeName"
          @tab-click="handleClick"
          style="padding: 0 10px"
        >
          <el-tab-pane label="任务中车辆" name="first">
            <!-- 数据表格 -->
            <el-table
              :data="tableData"
              border
              style="width: 100%"
              height="300px"
            >
              <el-table-column
                prop="name"
                label="任务名称"
                header-align="center"
                min-width="280"
              ></el-table-column>
              <el-table-column
                prop="numberPlate"
                header-align="center"
                align="center"
                label="车牌号"
                min-width="110"
                show-overflow-tooltip
              >
                <template slot-scope="scope">{{
                  scope.row.car && scope.row.car.numberPlate
                }}</template>
              </el-table-column>
              <el-table-column
                prop="username"
                header-align="center"
                align="center"
                label="司机名称"
                min-width="110"
                show-overflow-tooltip
              >
                <template slot-scope="scope">{{
                  scope.row.car &&
                    scope.row.car.driver &&
                    scope.row.car.driver.username
                }}</template>
              </el-table-column>
              <el-table-column
                prop="mobile"
                header-align="center"
                align="center"
                label="电话"
                min-width="130"
                show-overflow-tooltip
              >
                <template slot-scope="scope">{{
                  scope.row.car &&
                    scope.row.car.driver &&
                    scope.row.car.driver.mobile
                }}</template>
              </el-table-column>
              <el-table-column
                prop="containerDeliveryPoint"
                label="拉运去向"
                header-align="center"
                align="center"
              >
              <template slot-scope="scope">{{
                  scope.row.container && scope.row.container.containerDeliveryPoint
                }}</template>
              </el-table-column>
              <el-table-column
                prop="startTime"
                label="任务开始时间"
                min-width="140"
                header-align="center"
                align="center"
              >
              </el-table-column>
            </el-table>
            <!-- 分页器 -->
            <div class="block">
              <el-pagination
                class="block"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[5, 10, 20, 40]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pageTotal"
              ></el-pagination>
            </div>
          </el-tab-pane>
          <!-- 报警部分 -->
          <el-tab-pane label="报警列表" name="second">
            <el-table
              :data="tableDataTow"
              border
              style="width: 100%"
              height="300px"
            >
              <el-table-column
                prop="name"
                label="名称"
                min-width="250"
                header-align="center"
                align="leftt"
              >
              </el-table-column>
              <el-table-column
                prop="alarmAddress"
                header-align="center"
                align="left"
                label="位置"
              >
              </el-table-column>
              <el-table-column
                prop="alarmLiquidValue"
                label="当前液位(米)"
                header-align="center"
                align="center"
              >
              </el-table-column>
            <el-table-column
                prop="containerWarningLiquidValue"
                label="预警液位(米)"
                header-align="center"
                align="center"
              >
              </el-table-column>
              <!-- 1:处理中 2:处理完成 -->
              <el-table-column
                prop="status"
                header-align="center"
                align="center"
                label="处理状态"
                min-width="100"
                show-overflow-tooltip
              >
                <template slot-scope="scope">{{
                  statusMap[scope.row.status]
                }}</template>
              </el-table-column>
              <el-table-column
                prop="alarmTime"
                min-width="140"
                label="报警时间"
                header-align="center"
                align="center"
              >
              </el-table-column>
            </el-table>
            <!-- 分页器 -->
            <div class="block">
              <el-pagination
                class="block"
                @size-change="handleSizeChangeTow"
                @current-change="handleCurrentChangeTow"
                :current-page="currentPageTow"
                :page-sizes="[5, 10, 20, 40]"
                :page-size="pageSizeTow"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pageTotalTow"
              ></el-pagination>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </transition>
  </div>
</template>

<script>
import { fullscreenById } from "@/utils/common";
export default {
  data() {
    return {
      onlineCarInfo: {
        onlineCarCount: 0,
        offlineCarCount: 0
      },
      weatherInfo: {
        windDirection: "西北",
        windPower: "≤3",
        weather: "多云",
        temperature: 11
      },
      maxHeight: document.documentElement.clientHeight - 78,
      fullscreen: false,

      onlineContainer: 0,
      // 表格显示隐藏
      collectShow: false,
      carList: [],
      containerList: [],
      statusMap: {
        "0": "待处理",
        "1": "正在处理"
        // '2': '已处理'
      },
      map: null,
      satellite: new AMap.TileLayer.Satellite(),
      roadNet: new AMap.TileLayer.RoadNet(),
      // defaultLayer: AMap.TileLayer.Satellite(),
      containerMarkerList: [],
      carMarkerList: [],
      containerIndex: 0,
      stopInfoTimer: false,
      conImg0: require("@/assets/img/map/lan.png"),//正常
      conImg1: require("@/assets/img/map/hong.png"),//报警
      conImg2: require("@/assets/img/map/chizi.png"),//在线

      carImg0: require("@/assets/img/map/car0.png"),
      carImg1: require("@/assets/img/map/car1.png"),
      carImg2: require("@/assets/img/map/car2.png"),
      carImg3: require("@/assets/img/map/car3.png"),
      isSatellite: false,
      isFullScreen: false,
      timer: null,
      containerInfoTimer: null,

      //   分页最初显示那一页
      currentPage: 1,
      currentPageTow: 1,
      //   显示个数
      pageSize: 5,
      pageSizeTow: 5,
      //   总条数
      pageTotal: 400,
      pageTotalTow: 400,
      //   标签页变量
      activeName: "first",
      tableData: [
        {
          numberPlate: "", //车牌号
          carCapacity: "", //车辆载重
          fleetName: "", //车队
          userName: "", //驾驶员
          tel: "", //电话
          planCount: "", //计划收运数
          containerDeliveryPoint: "" //拉运去向
        }
      ],
      tableDataTow: []
    };
  },
  mounted() {
    this.refresh();
    this.refreshTow();
    this.init();
    this.getCarInfo();
  },
  beforeDestroy() {
    clearInterval(this.timer);
    this.timer = null;
    clearInterval(this.containerInfoTimer);
    this.containerInfoTimer = null;
  },
  methods: {
    init() {
      const that = this;
      var traffic = new AMap.TileLayer.Traffic({
        autoRefresh: true, //是否自动刷新，默认为false
        interval: 180 //刷新间隔，默认180s
      });
      // 初始化地图
      this.map = new AMap.Map("container",
        {
        rotateEnable: false,
        showBuildingBlock: true,
        center: [120.145407, 35.927715],
        zoom: 17,
        // mapStyle: "amap://styles/whitesmoke",
        // layers: [traffic, new AMap.TileLayer.Satellite()]
      });
      this.map.on("complete", () => {
        that.getContainerList();

        setTimeout(() => {
          that.map.setFitView();
          // 定义弹出容器信息窗口
          that.setContainerInfoTimer();
          that.getCarList();
        }, 2000);

        that.timer = setInterval(() => {
          that.getCarList();
          that.getContainerList();
          this.getCarInfo();
        }, 10000);
      });
      AMap.plugin("AMap.Weather", function() {
        //创建天气查询实例
        var weather = new AMap.Weather();

        //执行实时天气信息查询
        weather.getLive("青岛市", function(err, data) {
          console.log(err, data);
          that.weatherInfo.weather = data.weather;
          that.weatherInfo.windDirection = data.windDirection;
          that.weatherInfo.windPower = data.windPower;
          that.weatherInfo.temperature = data.temperature;
        });
      });
    },
    //获取在线车辆信息
    getCarInfo() {
      this.$http({
        url: this.$http.adornUrl("/sign/signcar/getCarCountToday"),
        method: "post"
      }).then(({ data }) => {
        if (data && data.code === 0) {
          console.log(data.data);
          this.onlineCarInfo.onlineCarCount = data.data.onlineCarCount;
          this.onlineCarInfo.offlineCarCount = data.data.offlineCarCount;
        } else {
        }
      });
    },
    getContainerList() {
      this.$http({
        url: this.$http.adornUrl("/sign/signcontainer/realList"),
        method: "post"
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.containerList = data.list;
          this.onlineContainer = data.onlineCount;
        } else {
          this.containerList = [];
        }
        this.initContainerMarkers();
      });
    },
    initContainerMarkers() {
      this.map.remove(this.containerMarkerList);
      this.containerMarkerList = this.containerList.map(container => {
        return this.createContainerMarker(container);
      });
    },
    setContainerInfoTimer() {
      if (this.containerInfoTimer) {
        clearInterval(this.containerInfoTimer);
        this.containerInfoTimer = null;
      }
      const that = this;
      this.containerInfoTimer = setInterval(() => {
        if (!this.stopInfoTimer) {
          const container = that.containerList[that.containerIndex];
          const marker = that.containerMarkerList[that.containerIndex];
          that
            .$http({
              url: that.$http.adornUrl(
                "/sign/signcontainer/info/" + container.id
              ),
              method: "post"
            })
            .then(({ data }) => {
              if (data && data.code === 0) {
                const curContainer = data.signContainer;

                that.map.clearInfoWindow();

                const currentValue = curContainer.sensorValue.toFixed(2);
                // 当前液位：${curContainer.sensorValue}米<br>
                // 预警液位：${curContainer.containerWarningLiquidValue}米<br>
                // 集水池高度：${curContainer.containerCapacity}米

                const infoWindow = new AMap.InfoWindow({
                  isCustom: true,
                  content: `<div class="map-window"><span class="map-window-title">集水池名称：${curContainer.name}</span><br>
                  当前液位：${currentValue}米<br>
                  </div>`,
                  offset: new AMap.Pixel(0, -20)
                });
                infoWindow.open(that.map, marker.getPosition());

                marker.setContent(that.getContainerMarkerContent(curContainer));
                // marker.setOffset(new AMap.Pixel(-13, -13))
                marker.setTop(true);
              }
            });

          if (that.containerIndex < that.containerList.length - 1) {
            that.containerIndex++;
          } else {
            that.containerIndex = 0;
          }
        }
      }, 10000);
    },
    createContainerMarker(container) {
      if (!container.lon || !container.lat) {
        return;
      }
      let content = this.getContainerMarkerContent(container);
      let marker = new AMap.Marker({
        title: container.name,
        content: content,
        map: this.map,
        zIndex: 300,
        position: new AMap.LngLat(container.lon, container.lat),
        clickable: true,
        offset: new AMap.Pixel(-13, -13),
        extData: container
      });
      const that = this;
      marker.on("click", e => {
        that.$emit("containerChange", container);
      });

      marker.on("mouseover", e => {
        this.$http({
          url: this.$http.adornUrl("/sign/signcontainer/info/" + container.id),
          method: "post"
        }).then(({ data }) => {
          if (data && data.code === 0) {
            const curContainer = data.signContainer;

            that.stopInfoTimer = true;
            that.map.clearInfoWindow();

            const containerDeliveryPoint = curContainer.containerDeliveryPoint;
            const currentValue = curContainer.sensorValue.toFixed(2);
            const containerWarningLiquidValue =curContainer.containerWarningLiquidValue.toFixed(2);
            // 当前液位：${curContainer.sensorValue}米<br>
            // 预警液位：${curContainer.containerWarningLiquidValue}米<br>
            // 集水池高度：${curContainer.containerCapacity}米

            const infoWindow = new AMap.InfoWindow({
              isCustom: true,
              content: `<div class="map-window"><span class="map-window-title">集水池名称：${curContainer.name}</span><br>
                当前液位：${currentValue}米<br>
                预警液位：${containerWarningLiquidValue}米<br>
                拉运去向：${containerDeliveryPoint}<br>
                </div>`,
              offset: new AMap.Pixel(0, -20)
            });
            infoWindow.open(that.map, marker.getPosition());

            marker.setContent(that.getContainerMarkerContent(curContainer));
            // marker.setOffset(new AMap.Pixel(-13, -13))
            marker.setTop(true);
          }
        });
      });

      marker.on("mouseout", e => {
        that.map.clearInfoWindow();
        this.stopInfoTimer = false;
      });
      return marker;
    },
    getContainerMarkerContent(container) {
      var alarmStatus = 0;
      if (container.sensorValue > 0) {
        alarmStatus = 2;
        if (container.sensorValue >= container.containerWarningLiquidValue) {
          alarmStatus = 1;
        }
      }
      const content = `<div style="display:flex;align-items:center;justify-content:center;">
        <img style="width: 26px" class="container-marker-img" src='${
          this["conImg" + alarmStatus]
        }' />
      </div>`;
      return content;
    },
    // getSelContainerMarkerContent(container) {
    //   const content = `<div style="display:flex;align-items:center;justify-content:center;">
    //     <img style="width: 32px" class="container-marker-img-sel" src='${this["selConImg" + container.status]
    //     }' />
    //   </div>`;
    //   return content;
    // },
    getCarList() {
      this.$http({
        url: this.$http.adornUrl("/sign/signcar/realList"),
        method: "post"
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.carList = data.list;
        } else {
          this.carList = [];
        }
        this.initCarMarkers();
      });
    },
    initCarMarkers() {
      // this.map.remove(this.carMarkerList);
      this.carMarkerList = this.carList.map(car => {
        return this.createCarMarker(car);
      });
    },
    createCarMarker(car) {
      if (!car.carLonLat) {
        return;
      }
      if (!car.carLonLat.lon) {
        return;
      }

      if (!car.carLonLat.lat) {
        return;
      }

      let content = this.getCarMarkerContent(car);
      let marker = new AMap.Marker({
        title: car.numberPlate,
        content: content,
        map: this.map,
        zIndex: 300,
        position: new AMap.LngLat(car.carLonLat.lon, car.carLonLat.lat),
        clickable: true,
        offset: new AMap.Pixel(-7, -13),
        extData: car.carLonLat
        // angle: car.carLonLat.direction
      });
      const that = this;
      marker.on("click", e => {
        that.$emit("carChange", car);
      });

      marker.on("mouseover", e => {
        this.$http({
          url: this.$http.adornUrl("/sign/signcar/info/" + car.id),
          method: "post"
        }).then(({ data }) => {
          if (data && data.code === 0) {
            const curCar = data.signCar;

            that.stopInfoTimer = true;
            that.map.clearInfoWindow();
            // 更新位置
            // marker.
            const infoWindow = new AMap.InfoWindow({
              isCustom: true,
              content: `<div class="map-window"><span class="map-window-title">车牌号：${curCar.numberPlate}</span><br>
                <span class="map-window-title">司机：${curCar.driver ? curCar.driver.username : '未绑定司机'}</span><br>
                <span class="map-window-title">电话：${curCar.driver ? curCar.driver.mobile : '--'}</span><br>
                车速：${curCar.carLonLat.speed} km/h <br>
                上传时间：${curCar.carLonLat.dataTime}
                </div>`,
              offset: new AMap.Pixel(0, -20)
            });
            infoWindow.open(that.map, marker.getPosition());

            marker.setContent(that.getCarMarkerContent(curCar));
            // marker.setOffset(new AMap.Pixel(-13, -13))
            marker.setTop(true);
          }
        });
      });

      marker.on("mouseout", e => {
        that.map.clearInfoWindow();
        that.stopInfoTimer = false;
      });
      return marker;
    },
    getCarMarkerContent(car) {
      const curTime = Date.now();
      const dataTime = new Date(car.carLonLat.dataTime).getTime()
      if (dataTime < curTime - 3600000) {
        // 设置离线状态
        car.status = "3"
      }
      const content = `<div style="display:flex;align-items:center;justify-content:center;flex-direction:column;width:120px">
        <img style="width: 14px;transform: rotate(${
          car.carLonLat.direction
        }deg)" class="car-marker-img" src='${this["carImg" + car.status]}' />
        <div style="font-size:12px;width:60px;border:1px solid #4D9CF5;border-radius:3px;text-align:center;background:linear-gradient(-90deg, #005DD1, #4D9CF5)">
          <span style="color:white">${car.carLonLat.speed} (km/h)</span> 
          </div>
      </div>`;
      return content;
    },
    toogleLayer() {
      this.isSatellite = !this.isSatellite;
      if (this.isSatellite) {
        this.map.add([this.satellite, this.roadNet]);
      } else {
        this.map.remove([this.satellite, this.roadNet]);
      }
    },
    toogleFullScreen() {
      this.isFullScreen = fullscreenById("car-map", this.isFullScreen);
    },

    // ------------工作台按钮方法---------------
    //   标签页切换事件
    handleClick(tab, event) {},
    // 分页点击事件
    handleSizeChange(val) {
      this.pageSize = val;
      this.refresh();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.refresh();
    },
    // 报警部分分页器
    handleSizeChangeTow(val) {
      this.pageSizeTow = val;
      this.refreshTow();
    },
    handleCurrentChangeTow(val) {
      this.currentPageTow = val;
      this.refreshTow();
    },

    //正在收运的任务车辆列表
    refresh() {
      let that = this;
      this.$http({
        url: this.$http.adornUrl(`/sign/signtask/listByQo`),
        data: this.$http.adornData({
          page: that.currentPage,
          limit: that.pageSize,
          status: "1"
        }),
        method: "post"
      }).then(({ data }) => {
        var list = data.page.list;
        if (data.code == 0 && list.length > 0) {
          that.tableData = list;
          that.pageTotal = data.page.totalCount;
        }
      });
    },
    // 报警的集水池报警列表
    refreshTow() {
      let that = this;
      this.$http({
        url: this.$http.adornUrl(`/sign/signcontaineralarm/listOfNoFinish`),
        data: this.$http.adornData({
          page: that.currentPageTow,
          limit: that.pageSizeTow,
          status: "2"
        }),
        method: "post"
      }).then(({ data }) => {
        var list = data.page.list;
        if (data.code == 0 && list.length > 0) {

          list.map((item, index) => {
            item.alarmLiquidValue = item.alarmLiquidValue.toFixed(3)
          })
     
          that.tableDataTow = list;

          that.pageTotalTow = data.page.totalCount;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.map-com.monitor-map {
  position: relative;
  height: 100%;

  .weatherDiv {
    position: absolute;
    top: 20px;
    left: 20px;
    height: 175px;
    background: rgba(2, 23, 48, 0.4);
    border-radius: 5px;
    color: white;
    padding: 5px;

    .carContainer{

      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;

      padding: 0 5px;
              .carImage{
          transform:rotate(90deg);
          width:15px;
          height: 28px;
          margin-right: 10px;
      } 

    }

  }




  .container {
    position: relative;
    padding: 0;
    width: 100%;
    height: 100%;
    background-color: #f5f5f5;
  }

  .tool-right {
    position: absolute;
    right: 10px;
    top: 10px;

    .tool-btn {
      width: 40px;
      height: 40px;
      padding: 6px;
      cursor: pointer;
    }
  }

  .collect {
    width: 85%;
    position: absolute;
    right: 10%;
    bottom: 0;
    background-color: #fff;
    z-index: 999;
    border-radius: 8px 8px 0px 0px;
    filter: progid:DXImageTransform.Microsoft.Shadow(color=#909090, direction=120, strength=4);
    -moz-box-shadow: 2px 2px 10px #909090;
    -webkit-box-shadow: 2px 2px 10px #909090;
    box-shadow: 2px 2px 10px #909090;

    .btn {
      width: 120px;
      height: 32px;
      line-height: 32px;
      background: rgba(255, 255, 255, 1);
      border-radius: 8px 8px 0px 0px;
      font-size: 15px;
      font-family: PingFang SC;
      font-weight: 500;
      color: rgba(22, 127, 255, 1);
      position: absolute;
      top: -32px;
      right: 50px;
      display: flex;
      justify-content: space-around;
    }

    .block {
      background-color: #fff;
      margin: 0 0;
      padding: 2px 0;
      height: 35px;
    }

    .vehicle {
      // width: 32%;
      position: absolute;
      top: 12px;
      right: 30px;
      font-size: 13px;
      font-family: PingFang SC;
      font-weight: 300;
      display: flex;
      justify-content: space-between;

      span {
        margin: 0 10px;
      }
    }
  }

  .iconFrom {
    width: 120px;
    height: 32px;
    line-height: 32px;
    background: rgba(255, 255, 255, 1);
    border-radius: 8px 8px 0px 0px;
    font-size: 15px;
    font-family: PingFang SC;
    font-weight: 500;
    color: rgba(22, 127, 255, 1);
    position: absolute;
    right: 13%;
    bottom: 20px;
    display: flex;
    justify-content: space-around;
    filter: progid:DXImageTransform.Microsoft.Shadow(color=#909090, direction=120, strength=4);
    -moz-box-shadow: 2px 2px 10px #909090;
    -webkit-box-shadow: 2px 2px 10px #909090;
    box-shadow: 2px 2px 10px #909090;
  }
}
</style>

<style lang="scss">
.input-with-point {
  .el-input-group__append {
    background: #0080ff;

    .el-button {
      color: #fff;
    }
  }

  .el-input-group__append,
  .el-input-group__prepend {
    border: 0;
  }
}
</style>
